package com.hanelalo.gaugepro;

import static org.junit.jupiter.api.Assertions.assertEquals;

import com.hanelalo.gaugepro.controller.PayAmountRequest;
import com.hanelalo.gaugepro.controller.PayAmountResponse;
import com.thoughtworks.gauge.AfterScenario;
import com.thoughtworks.gauge.BeforeScenario;
import com.thoughtworks.gauge.Step;
import com.thoughtworks.gauge.datastore.ScenarioDataStore;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class FirstGauge {

  @BeforeScenario(tags = "FirstGauge")
  public void beforeScenario(){
    System.out.println("First Gauge Before Scenario");
  }

  @AfterScenario(tags = "FirstGauge")
  public void afterScenario(){
    System.out.println("First Gauge After Scenario");
  }

  @Step("Given <user>有<discount>折优惠券, 账单金额为<amount>元")
  public void stepGiven(String user, String discount, String amount) {
    System.out.println("当前结算用户为: " + user);
    System.out.println("当前折扣为 " + discount + " 折");
    System.out.println("当前账单金额为: " + amount + " 元");
    ScenarioDataStore.put("amount", Double.parseDouble(amount));
    ScenarioDataStore.put("discount", Integer.parseInt(discount) * 10);
  }

  @Step("When 到前台结账")
  public void stepWhen() {
    System.out.println("开始结账了...");
    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<PayAmountRequest> request =
        new HttpEntity<>(
            new PayAmountRequest()
                .setDiscount((Integer) ScenarioDataStore.get("discount"))
                .setAmount((Double) ScenarioDataStore.get("amount")),
            provideHeaders());
    ResponseEntity<PayAmountResponse> responseEntity = restTemplate
        .postForEntity("http://localhost:8080/calc", request, PayAmountResponse.class);
    System.out.println(responseEntity.getBody());
    ScenarioDataStore.put("response",responseEntity.getBody());
  }

  private HttpHeaders provideHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
    return headers;
  }

  @Step("Then 最终的支付金额为<realAmount>")
  public void stepThen(String realAmount) {
    System.out.println("终于走到断言了,淦...");
    PayAmountResponse response= (PayAmountResponse) ScenarioDataStore.get("response");
    assertEquals(Double.parseDouble(realAmount), response.getRealAmount());
  }

}
